#include "eeprom.h"

uint32_t eeprom_read_word(uint32_t address)
{
    return *(__IO uint32_t *)address;
}

uint16_t eeprom_read_half_word(uint32_t address)
{
    return *(__IO uint16_t *)address;
}


uint8_t eeprom_read_byte(uint32_t address)
{
    return *(__IO uint8_t *)address;
}

void eeprom_write(eeprom_data_t data)
{
    uint32_t i = 0;
 
    HAL_FLASHEx_DATAEEPROM_Unlock();
    /*clear  write proctect flag*/
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR);
 
    for(i = 0; i < data.len; i++){
		
        if(HAL_FLASHEx_DATAEEPROM_Program(FLASH_TYPEPROGRAM_WORD, data.address + (i * 4), data.eeprom_data[i]) != HAL_OK)
            app_fault_handle(APP_EEPROM_WRITE_ERROR);
    }
 
    HAL_FLASHEx_DATAEEPROM_Lock();
}

void eeprom_erase(uint32_t word_number, uint32_t address)
{
    if(word_number > (EEPROM_SIZE / 4))
        app_fault_handle(APP_EEPROM_ERROR);
    
    if((address > EEPROM_END_ADDR) || (address < EEPROM_START_ADDR))
       app_fault_handle(APP_EEPROM_ERROR);
 
    HAL_FLASHEx_DATAEEPROM_Unlock();
    /*clear  write proctect flag*/
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR);
    
    for(uint32_t i = 0; i < word_number; i++)
        if(HAL_FLASHEx_DATAEEPROM_Erase(address + (i * 4)) != HAL_OK)
            app_fault_handle(APP_EEPROM_ERASE_ERROR);
 
    HAL_FLASHEx_DATAEEPROM_Lock();
}

